from common import BaseRequestHandler
from datetime import datetime
from google.appengine.api import users
from google.appengine.api.users import User
from lib.common_cards import get_color, get_suit, get_rank, random, \
    NUMBER_OF_CARDS_WITH_JOKERS, NUMBER_OF_RANKS
from lib.dbobjects import Profiler

_WINNING_FACTORS = {"COLOR":1,
                    "SUIT":3,
                    "RANK":12,
                    "CARD":51}

_WON_BET = {"COLOR":lambda x, y: x == get_color(y),
            "SUIT": lambda x, y: x == get_suit(y),
            "RANK": lambda x, y: x == get_rank(y),
            "CARD": lambda x, y: x == y}

def get_outcomes():
    outcomes = []
    for i in ("COLOR", "SUIT", "RANK", "CARD"):
        outcomes.append([i, str(_WINNING_FACTORS[i]) + "x"])
    return outcomes

# The guess is in the proper format
## For example for "SUIT" the guess should be either 0, 1, 2, or 3
## The answer is a card from 0 to 53
def won_bet(property, guess, answer):
    return _WON_BET[property.upper()](guess, answer)
    

class Level4Page(BaseRequestHandler):
    
    def get(self):
        if (users.is_current_user_admin()):
            self.redirect('/admin')
        else:
            information = "This is the poker roulette. It's a great " + \
                    "opportunity to try out the famous doubling up " + \
                    "strategy without having to go to casino. " + \
                    "You can bet on color, suit, rank, and jokers. Enjoy!"
            self.display(information=information)
    
    def post(self):
        
        # Look up profiler info and read the form values
        profilers_query = Profiler.all().filter("user =",
                users.get_current_user()).order('-modified')
        profiler = profilers_query.get()
        
        bet_total = 0
        bet = {}
        for i in ("color", "suit", "rank", "card"):
            bet[i] = int(self.request.get('bet_' + i))
            bet_total += bet[i]
        
        # If somehow the bet was bigger than the money, go home
        if profiler.money < self.LEVEL4_CUTOFF or bet_total > profiler.money:
            self.redirect('/')
        else:
            # Generate the card
            generated_card = random.randint(0,
                    NUMBER_OF_CARDS_WITH_JOKERS - 1)
            result_image = "/images/card_" + str(generated_card) + ".png"
            payoff = 0
            result_messages = []
            # Read the values from the template
            guess = {}
            for i in ("color", "suit", "rank", "card"):
                guess[i] = int(self.request.get(i + '_guess'))
                if bet[i] > 0:
                    if won_bet(i, guess[i], generated_card):
                        payoff += bet[i] * _WINNING_FACTORS[i.upper()]
                        win_amount = bet[i] * (_WINNING_FACTORS[i.upper()]+1)
                        message = "You guessed the " + str(i) + ", " + \
                                "since you bid " + str(bet[i]) + \
                                " you get " + str(win_amount)
                        result_messages.append(message)
                    else:
                        payoff -= bet[i]
                        result_messages.append("You lost %d on the %s bid" %
                                (bet[i], i))
            casino_query = Profiler.all().filter("user =",
                    User("Casino")).order('-modified')
            casino = casino_query.get()
            if casino is None:
                casino = Profiler(user = User("Casino"),
                        nickname = "Robert De Niro", money = 0)
            profiler.money += payoff
            casino.money -= payoff
            profiler.modified = datetime.now()
            profiler.hands_per_level[3] += 1
            casino.put()
            profiler.put()
            
            if profiler.money < 1:
                self.redirect('/')
            else:
                # Put everything we want to put into template_values
                template_values = {'result_messages': result_messages,
                                   'result_image': result_image}
                self.display(template_values)
        
    def display(self, passed_template_values=[], information=None):
        profilers_query = Profiler.all().filter("user =",
                users.get_current_user()).order('-modified')
        profiler = profilers_query.get()
        # Prepare the next round
        rank_images = []
        for i in xrange(NUMBER_OF_RANKS):
            rank_images.append("/images/card_" + str(i) + ".png")
        card_images = []
        for i in xrange(2):
            card_images.append("/images/card_" +
                    str(NUMBER_OF_CARDS_WITH_JOKERS-2+i) + ".png")
        template_values = {'level_name': self.LEVEL4_NAME,
                           'profiler': profiler,
                           'rank_images': rank_images,
                           'card_images': card_images}
        if information is not None and profiler.hands_per_level[3] < 10:
            template_values['information'] = information
        template_values.update(passed_template_values)
        self.generate('level4.html', template_values)